package com.ruoyi.backend.consumer;

import com.rabbitmq.client.Channel;
import com.ruoyi.backend.config.InversionDelayRabbitmqConfig;
import com.ruoyi.backend.constant.InversionConstants;
import com.ruoyi.backend.controller.EcologicalController;
import com.ruoyi.backend.mapper.FileMapper;
import com.ruoyi.backend.service.FileService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component

public class MQConsumer {

    @Autowired
    FileService fileService;

    /**
     * 处理延迟队列中的反演文件删除消息
     * 从死信队列中接收消息，尝试删除指定的反演文件
     *
     * @param message 来自RabbitMQ的消息，包含要删除的文件名
     * @param channel RabbitMQ通道，用于发送确认或拒绝消息
     * @throws IOException 当处理消息或与RabbitMQ通信时发生IO异常
     */
    @RabbitListener(queues = InversionDelayRabbitmqConfig.DEAD_LETTER_QUEUE)
    public void inversionDelayConsumer(Message message, Channel channel) throws IOException {
        try {
            String fileName = new String(message.getBody());
            boolean result = false;
            result = fileService.deleteFile(InversionConstants.INVERSION_BUCKET_NAME, fileName);
            if (result){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }
}
